package dao

import (
	"fmt"
	"github.com/go-stack/stack"
	"log"
	"net/http"
	"os"
	"time"
)

/**
LogRequest
*/
func LogRequest(r *http.Request) {
	url := GetCurrentUrl(r)
	logString := fmt.Sprintf("[%s] [%s] [%s - %s] [%s] [%s] [%s]\n",
		time.Now().Format(TimeLayout),
		GetCurrentIp(r),
		r.Method,
		url,
		r.Header.Get("User-Agent"),
		r.Header.Get("Referer"),
		r.Header.Get("Cookie"),
	)
	//fmt.Println(logString)
	//追加写入文件
	fd, _ := os.OpenFile(RunCFG.RequestLogFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
	fd.Write([]byte(string(logString)))
	defer fd.Close()
}

/**
LogError
*/
func LogError(err error) {
	log.Print(err)
	c := stack.Caller(2)
	log.SetPrefix("\n")
	log.Print(c)         // "source.go:10"
	log.Printf("%+v", c) // "pkg/path/source.go:10"
	log.Printf("%n", c)  // "DoTheThing"

	s := stack.Trace().TrimRuntime()
	log.Print(s) // "[source.go:15 caller.go:42 main.go:14]"
	log.Println()
}

/**
LogServiceStart
*/
func LogServiceStart() {
	logString := fmt.Sprintf("[%s] [ServiceStart] [Listen:%s Port:%s]",
		time.Now().Format(TimeLayout), HttpCfg.Listen, HttpCfg.Port)
	fmt.Println(logString)

	//追加写入文件
	fd, _ := os.OpenFile(RunCFG.ServiceStartLogFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
	fd.Write([]byte(string(logString)))
	defer fd.Close()
}
